package tech.mobi.child;

import tech.mobi.child.service.MainService;
import tech.mobi.child.service.UpdateVersionService;
import tech.mobi.child.utils.Configuration;
import tech.mobi.child.utils.DebugUtil;
import tech.mobi.child.utils.UpdateManager;
import tech.mobi.child.R;

import org.mymmsc.android.app.util.XmlResult;


import com.umeng.update.UmengUpdateAgent;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class MainAct_back extends TabActivity implements OnClickListener {
	public static final int REQ_UPDATE = 1;
	public static final int REQ_UPDATE_SUCCEED = 2;
	private TabHost tabHost;
	public static MainAct_back mainUI;
	public RadioGroup rgtab;
	
	public static final String LAST_UPDATE_DATE = "LastUpdateDate";
	public static final String LAST_UPDATE_DATA = "LastUpdateData";

	public MainAct_back() {
		mainUI = this;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.maintabs);

		Intent intent = this.getIntent();
		if (intent != null && "auto".equals(intent.getStringExtra("flag"))) {
			// 友盟自动更新
			UmengUpdateAgent.setUpdateOnlyWifi(false);
			UmengUpdateAgent.update(this);
		}

		tabHost = this.getTabHost();

		// 首页
		TabSpec tsMoney = tabHost.newTabSpec("TS_1").setIndicator("TS_1")
				.setContent(new Intent(this, FirstClientAct.class));
		tabHost.addTab(tsMoney);
		// 个人中心
		TabSpec tsInfo = tabHost.newTabSpec("TS_2").setIndicator("TS_2")
				.setContent(new Intent(this, SecondClientAct.class));
		tabHost.addTab(tsInfo);
		// 消息
		TabSpec tsMeal = tabHost.newTabSpec("TS_3").setIndicator("TS_3")
				.setContent(new Intent(this, ThirdClientAct.class));
		tabHost.addTab(tsMeal);
		// 更多
		TabSpec tsSettings = tabHost.newTabSpec("TS_4").setIndicator("TS_4")
				.setContent(new Intent(this, FourthClientAct.class));
		tabHost.addTab(tsSettings);

		tabHost.setCurrentTabByTag("TS_1");

		rgtab = (RadioGroup) this.findViewById(R.id.main_radio);
		rgtab.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(RadioGroup group, int checkedId) {

				switch (checkedId) {

				case R.id.rbtnFirst:// 首页
					tabHost.setCurrentTabByTag("TS_1");

					break;
				case R.id.rbtnSecond:// 个人中心
					tabHost.setCurrentTabByTag("TS_2");

					break;
				case R.id.rbtnThird:// 消息
					tabHost.setCurrentTabByTag("TS_3");

					break;
				case R.id.rbtnFourth:// 更多
					tabHost.setCurrentTabByTag("TS_4");

					break;
				}
			}
		});
		//handler.sendEmptyMessage(REQ_UPDATE);// 请求检查是否有新版本
	}

	
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case REQ_UPDATE:
				new UpdateTask().execute(REQ_UPDATE);
				break;
			case REQ_UPDATE_SUCCEED:
				showUpdateDialog((XmlResult) msg.obj);
				break;

			}
			super.handleMessage(msg);
		}

	};

	private void showUpdateDialog(final XmlResult xmlResult) {
		String message = xmlResult.message;
		Dialog dialog = new AlertDialog.Builder(this)
				.setTitle(R.string.main_tab_update_title)
				.setMessage(
						"是否更新?\r\n"
								+ (message == null ? "" : "更新内容：" + message))
				// 设置内容
				.setPositiveButton(R.string.dialog_ok,// 设置确定按钮
						new DialogInterface.OnClickListener() {

							@SuppressWarnings("unused")
							public void onClick(DialogInterface dialog,
									int which) {
								Uri uri = Uri.parse(xmlResult.content);
								// Intent intent = new
								// Intent(Intent.ACTION_VIEW,
								// uri);
								// startActivity(intent);
								// finish();
								String strFlag = "1";
								if (xmlResult.message.contains("正常使用")) {
									strFlag = "0";
								}
								UpdateManager updateManager = new UpdateManager(
										mainUI, Configuration.APP_NAME, uri
												.toString(), strFlag);

							}
						})
				.setNegativeButton(R.string.dialog_cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								if (xmlResult.message.contains("正常使用")) {
									Toast.makeText(MainAct_back.this,
											"请下载新版本后，正常使用日昌易通",
											Toast.LENGTH_LONG).show();

									if (MainService.isRunOfService) {
										if (MainService.isRun) {
											MainService.isRun = false;
										}
										MainService.isRunOfService = false;
										Intent intent = new Intent(
												MainAct_back.this, MainService.class);
										stopService(intent);
									}
									finish();
									android.os.Process
											.killProcess(android.os.Process
													.myPid());
								}

							}
						}).create();// 创建
		// 显示对话框
		dialog.show();
	}

	/**
	 * 检查是否有更新版本的Task
	 * 
	 * @author lijianguo
	 * 
	 */
	private final class UpdateTask extends AsyncTask<Integer, Void, Void> {

		@Override
		protected Void doInBackground(Integer... params) {
			int type = params[0];

			try {
				switch (type) {
				case REQ_UPDATE:
					PackageInfo info = getPackageManager().getPackageInfo(
							getPackageName(), 0);
					XmlResult ret = UpdateVersionService.update(
							Configuration.APP_NAME, info.versionName);

					if (ret.status.equals(Configuration.EXP_SUCCESS)) {
						Message message = handler.obtainMessage();
						message.obj = ret;
						message.what = REQ_UPDATE_SUCCEED;
						handler.sendMessage(message);
					}
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		DebugUtil.MyLog("Test", "MainAct  onKeyDown");
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			clickBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 点击Back键，返回上一级，或弹出退出UI
	 */
	public void clickBack() {
		Intent intent = new Intent(this, ExitClientAct.class);
		startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}

}
